<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false" style="padding-bottom: 30px">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基础信息">
            <a-row :gutter="48">
              <a-col :span="12">
                <a-form-model-item label="公司名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fileName">
                  <a-input :disabled="formDisabled" v-model="model.fileName" placeholder="请输入公司名称"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item
                  label="统一社会信用代码"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="enterpriseCreditCode"
                >
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.enterpriseCreditCode"
                    placeholder="请输入统一社会信用代码"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item
                  label="公司法人"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="legalRepresentative"
                >
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.legalRepresentative"
                    placeholder="请输入公司法人"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item
                  label="公司地址"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="enterpriseAddress"
                >
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.enterpriseAddress"
                    placeholder="请输入公司地址"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="公司级别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="companyLevel">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.companyLevel"
                    dictCode="company_level"
                    placeholder="请选择公司级别"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="liaison">
                  <a-input :disabled="formDisabled" v-model="model.liaison" placeholder="请输入联系人"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="liaisonMobile">
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.liaisonMobile"
                    placeholder="请输入联系电话"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="开户行" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bankName">
                  <a-input :disabled="formDisabled" v-model="model.bankName" placeholder="请输入开户行"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="银行账号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bankAccountNo">
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.bankAccountNo"
                    :max-length="32"
                    placeholder="请输入银行账号"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="关联部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deptId">
                  <j-select-depart placeholder="请选择关联部门" :disabled="formDisabled" v-model="model.deptId" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="创建人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep placeholder="请选择创建人" v-model="model.proposer" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="创建时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date
                    placeholder="请选择创建时间"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item
                  label="公司对应e签宝APPid"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="esignAppId"
                >
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.esignAppId"
                    placeholder="请输入公司对应e签宝APPid"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item
                  label="e签宝应用密钥"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="esignAppSecret"
                >
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.esignAppSecret"
                    placeholder="请输入e签宝应用密钥"
                  ></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="营业执照">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item
                  label="注册资本（万元）"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="registerCapital"
                >
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    :precision="2"
                    v-model="model.registerCapital"
                    placeholder="请输入注册资本（万元）"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="发证日期"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="issueCertificateDate"
                >
                  <j-date
                    placeholder="请选择发证日期"
                    v-model="model.issueCertificateDate"
                    :show-time="true"
                    date-format="YYYY-MM-DD"
                    :disabled="formDisabled"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="原件保管员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="custodian">
                  <!-- <select-user-by-dep
                    placeholder="请选择原件保管员"
                    v-model="model.custodian"
                    :disabled="formDisabled"
                  /> -->
                  <a-input :disabled="formDisabled" v-model="model.custodian" placeholder="请输入原件保管员"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachments">
                  <j-upload :disabled="formDisabled" v-model="model.attachments" :showToast="false" fileFormat=".pdf, .PDF" isSingle></j-upload>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="经营范围" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bussiness">
                  <a-textarea
                    :disabled="formDisabled"
                    :max-length="500"
                    v-model="model.bussiness"
                    rows="4"
                    placeholder="请输入经营范围"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="资质证书">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-button @click="handleAddChild" type="primary" style="margin-bottom: 10px" v-if="!formDisabled">新增</a-button>
                <a-table
                  ref="table"
                  bordered
                  size="small"
                  rowKey="key"
                  :components="draggableComponent"
                  :scroll="{x:scrollX}"
                  :columns="childColumns"
                  :dataSource="dataSource"
                  :loading="childLoading"
                  :pagination="false"
                >
                  <template slot="fileSlot" slot-scope="text">
                    <a @click="handleNewPre(text)">{{ text }}</a>
                  </template>
                  <span slot="action" slot-scope="text, record">
                    <a @click="handleData(record)">编辑</a>
                  </span>
                </a-table>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <ErpCertificationChildModal ref="childModal" @dataOne="modalOkhandle"></ErpCertificationChildModal>
    <watermark ref="watermarks" @ok="downloadOK"/>
      <a-modal
        title="请选择预览或下载"
        :visible="prebtnVisible"
        :footer="null"
        @cancel="handleNewPreCancel"
        :width="240"
      >
        <div style="text-align: center;">
          <a-button shape="circle" icon="search" @click="handlePreviews(prebtnFile)"/>
          <a-divider type="vertical"/>
          <a-button shape="circle" icon="download" @click="handleModals(prebtnFile)"/>
        </div>
      </a-modal>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { mapGetters } from 'vuex'
import moment from 'moment'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import ErpCertificationChildModal from './ErpCertificationChildModal.vue'
import { DragResizable } from '@/mixins/DragResizable'
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
import PreviewPdf from '@/utils/previewPdfPublic'
import { axios } from '@/utils/request'
import watermark from '@/views/erp/hr/certificatefile/companyQualification/modules/watermark.vue'
export default {
  name: 'ErpCompanyFilesForm',
  components: {
    SelectUserByDep,
    ErpCertificationChildModal,
    watermark,
  },
  mixins:[DragResizable],
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    var validatorEnterpriseCreditCode = async (rule, value, callback) => {
      if (value) {
        const that = this
        await getAction(this.url.queryByEnterpriseCreditCode, { enterpriseCreditCode: value }).then((res) => {
          if (res.success) {
            console.log(res.result)
            console.log(that.enterpriseCreditCode)
            console.log(value)
            if (res.result == '0') {
              that.onlyEnterpriseCreditCode = false
            } else if (res.result == '1' && that.enterpriseCreditCode == value) {
              that.onlyEnterpriseCreditCode = false
            } else {
              that.onlyEnterpriseCreditCode = true
            }
          } else {
            that.$message.warning(res.message)
          }
        })
        if (that.onlyEnterpriseCreditCode) {
          callback('统一社会信用代码已存在，请重新输入！')
          return
        }
        callback()
      }
      callback()
    }
    return {
      model: {
        delFlag: '0',
      },
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 },
      },
      confirmLoading: false,
      validatorRules: {
        fileName: [{ required: true, message: '请输入公司名称!', trigger: 'blur' }],
        enterpriseCreditCode: [
          { required: true, message: '请输入统一社会信用代码!', trigger: 'blur' },
          { validator: validatorEnterpriseCreditCode, trigger: 'blur' },
        ],
        legalRepresentative: [{ required: true, message: '请输入公司法人!', trigger: 'blur' }],
        // registerCapital: [
        //     { required: true, message: '请输入注册资本（万元）!', trigger: "blur"},
        //     { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' }
        // ],
        enterpriseAddress: [{ required: true, message: '请输入公司地址!', trigger: 'blur' }],
        companyLevel: [{ required: true, message: '请选择公司级别!', trigger: ['change', 'blur'] }],
        liaison: [{ required: true, message: '请输入联系人!', trigger: 'blur' }],
        liaisonMobile: [
          { required: true, message: '请输入联系电话!', trigger: 'blur' },
          {
            pattern: /^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/,
            message: '请输入正确的联系电话!',
          },
        ],
        bankName: [{ required: true, message: '请输入开户行!', trigger: 'blur' }],
        bankAccountNo: [
          { required: true, message: '请输入银行账号!', trigger: 'blur' },
          // { pattern: /^\d{10,25}$/, message: '请输入正确的银行账号!' },
        ],
        registerCapital: [{ required: true, message: '请输入注册资本!', trigger: 'blur' }],
        issueCertificateDate: [{ required: true, message: '请选择发证日期!', trigger: ['change', 'blur'] }],
        custodian: [{ required: true, message: '请输入原件保管员!', trigger: 'blur' }],
        attachments: [{ required: true, message: '请选择附件!', trigger: ['change', 'blur'] }],
        bussiness: [{ required: true, message: '请输入经营范围!', trigger: 'blur' }],
      },
      url: {
        add: '/api/erp/files/company/erpCompanyFiles/add',
        edit: '/api/erp/files/company/erpCompanyFiles/edit',
        queryById: '/api/erp/files/company/erpCompanyFiles/queryById',
        queryByEnterpriseCreditCode: '/api/erp/files/company/erpCompanyFiles/queryByEnterpriseCreditCode',
      },
      enterpriseCreditCode: null,
      onlyEnterpriseCreditCode: true,
      activeKey: ['1', '2', '3'],
      dataSource: [],
      childLoading: false,
      childColumns: [
        // {
        //   title: '序号',
        //   dataIndex: '',
        //   key:'rowIndex',
        //   width:60,
        //   align:"center",
        //   customRender:function (t,r,index) {
        //     return parseInt(index)+1;
        //   }
        // },
        {
          title: '证书种类',
          align: 'center',
          dataIndex: 'certificateType',
          ellipsis: true,
          width:120,
          customRender: (value, record, index) => {
            let text = ''
            if(!value){
              text = ''
            } else {
              text = filterMultiDictText(this.dictOptions['certificateType'], value + '')
            }
            return {
              children: text,
              attrs: { rowSpan: record.childspan },
            };
          },
        },
        {
          title:'证书名称',
          align:"center",
          dataIndex: 'certificateName',
          customRender: (value, record, index) => {
            if(!value){
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['certificateName'], value + '')
            }
          },
          ellipsis: true,
          width:120,
        },
        {
          title:'发证单位',
          align:"center",
          dataIndex: 'issueCertificateUnit',
          ellipsis: true,
          width:120,
        },
        {
          title:'发证日期',
          align:"center",
          dataIndex: 'issueCertificateDate',
          ellipsis: true,
          width:120,
        },
        {
          title:'有效期',
          align:"center",
          dataIndex: 'validPeriod',
          ellipsis: true,
          customRender: (text, r) => {
            if (r.isAlways==1) {
              return ''
            } else {
              return text
            }
          },
          width:120,
        },
        {
          title:'原件保管人',
          align:"center",
          dataIndex: 'custodian',
          ellipsis: true,
          width:120,
        },
        {
          title:'专利分类',
          align:"center",
          dataIndex: 'patentType',
          customRender: (text, r) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['patentType'], text + '')
            }
          },
          ellipsis: true,
          width:120,
        },
        {
          title:'附件',
          align:"center",
          dataIndex: 'attachments',
          scopedSlots: { customRender: 'fileSlot' },
          ellipsis: true,
          width:120,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          fixed: 'right',
          width:150,
          scopedSlots: {
          filterDropdown: 'filterDropdown',
          filterIcon: 'filterIcon',
          customRender: 'action' }
        }
      ],
      dictOptions:{},
      prebtnVisible: false,
      prebtnFile: ''
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    this.initDictConfig()
    if(this.disabled){
      this.childColumns.pop()
    }
    this.customKey = 'childColumns'
    this.childColumnswidth = this.childColumns.map(val => {
      return val.width
    })
    this.getCertificateName('')
  },
  methods: {
    ...mapGetters(['userInfo']),
    async getCertificateName(typeCode){
      let res = await getAction('/api/erp/basecertinfo/field/nameList',{ typeCode })
      if(res.success){
        this.$set(this.dictOptions, 'certificateName', res.result.map(val => {
          return {
            label: val.certName,
            value: val.id,
            text: val.certName
          }
        }))
      }
    },
    handleNewPre(value){
      this.prebtnVisible = true
      this.prebtnFile = value
    },
    handleNewPreCancel(){
      this.prebtnVisible = false
      this.prebtnFile = ''
    },
    handleModals(value){
      this.$refs.watermarks.visible = true
      this.$refs.watermarks.wValue = value
    },
    downloadOK(){
      getAction('/api/erp/files/company/erpCompanyFiles/downloadCertificate').then(result => {})
    },
    handlePreviews(value){
      let fileType = value.substr(-3)
      let text = `${this.userInfo().orgCodeTxt}-${this.userInfo().realname}-${this.userInfo().workNo}`
      let url = window.sessionStorage.getItem('baseUrl') + '/api/erpmng/sys/common/static/' + value
      axios({
        url: url,
        params: {},
        method:'get' ,
        responseType: 'blob',
      }).then(res=>{
        if(fileType==='pdf'){
          new PreviewPdf({
            blob: res,
            docTitle: fileType,
            isAddWatermark: true, // 是否需要添加水印
            watermark: { // watermark必填 里面可以不填
              type: 'canvas',
              text: text,
            }
          })
        }else{
          // location.href = url
          this.$message.error('非pdf文件不可查看')
        }
        
      })
    },
    initDictConfig(){
      initDictOptions('certificate_type').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'certificateType', res.result)
        }
      })
      initDictOptions('patent_type').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'patentType', res.result)
        }
      })
    },
    add() {
      this.edit(this.modelDefault)
      this.model.proposer = this.userInfo().empId //当前登录人
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss') //申请时间
    },
    edit(record) {
      this.$refs['form'].clearValidate()
      this.model = Object.assign({}, record)
      if (!!this.model.enterpriseCreditCode) {
        this.enterpriseCreditCode = this.model.enterpriseCreditCode
      } else {
        this.enterpriseCreditCode = null
      }
      if(this.model.id){
        let data = Object.assign([],this.model.certificateList)
        if(data.length){
          let carr = data.reduce((result,item) => {
            const key = item.certificateType
            if(!result[key]){
              result[key] = []
            }
            result[key].push(item)
            return result
          },{})
          let arr = []
          Object.keys(carr).map(zevel => {
            let len = carr[zevel].length
            arr.push(...carr[zevel].map((dItem,index) => {
              return {
                ...dItem,
                childspan: index === 0 ? len : 0
              }
            }))
          })
          this.dataSource = arr.map((item,index) => {
            return {
              ...item,
              key: index
            }
          })
        } else {
          this.dataSource = []
        }
      } else {
        this.dataSource = []
      }
      this.visible = true
      this[this.customKey].forEach((val,index) => {
        val.width = this[this.customKey+'width'][index]
      })
    },
    modalOkhandle(data,flag){
      if (flag) {
        this.dataSource.push(data)
      } else {
        this.dataSource.splice(data.key, 1, data);
      }
      let source = this.dataSource
      let carr = source.reduce((result,item) => {
        const key = item.certificateType
        if(!result[key]){
          result[key] = []
        }
        result[key].push(item)
        return result
      },{})
      let arr = []
      Object.keys(carr).map(zevel => {
        let len = carr[zevel].length
        arr.push(...carr[zevel].map((dItem,index) => {
          return {
            ...dItem,
            childspan: index === 0 ? len : 0
          }
        }))
      })
      this.dataSource = arr.map((item,index) => {
        return {
          ...item,
          key: index
        }
      })
    },
    handleData(record) {
      this.$refs.childModal.edit(record,this.dataSource)
      this.$refs.childModal.title = '编辑'
      this.$refs.childModal.disableSubmit = false
    },
    handleAddChild(){
      this.$refs.childModal.add(this.dataSource)
      this.$refs.childModal.title = '新增'
      this.$refs.childModal.disableSubmit = false
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          that.model.certificateList = that.dataSource
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
                that.$emit('unButtonDisable')
              }
            })
            .catch((error) => {
              that.$emit('unButtonDisable')
            })
            .finally(() => {
              that.confirmLoading = false
            })
        } else {
          that.$emit('unButtonDisable')
        }
      })
    },
  },
}
</script>
